package com.dbpms.pj.sys.controller;

import com.dbpms.pj.common.exception.ServiceException;
import com.dbpms.pj.common.pojo.JsonResult;
import com.dbpms.pj.sys.pojo.SysUser;
import com.dbpms.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Song Yu
 * @Date: 2020/10/20 19:13
 */

@RestController
@RequestMapping("/user/")
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    @RequestMapping("doFindPageObjects")
    public JsonResult findPageObjects(String username, @RequestParam Integer pageCurrent){
        return new JsonResult(sysUserService.findPageObjects(username,pageCurrent));
    }

    @RequestMapping("doValidById")
    public JsonResult doValidById(Integer id,Integer valid){
        sysUserService.updateValidById(id,valid);
        if(valid==1){
            return new JsonResult("已启用");
        }else if(valid==0){
            return new JsonResult("已禁用");
        }
        throw new ServiceException("参数不合法,valid="+valid);
    }

    @RequestMapping("doSaveObject")
    public JsonResult doSaveObject(SysUser entity,Integer[] roleIds){
        sysUserService.saveObject(entity,roleIds);
        return new JsonResult("save ok");
    }

    @RequestMapping("doFindObjectById")
    public JsonResult doFindObjectById(Integer id){
        return new JsonResult(sysUserService.findObjectById(id));
    }

    @RequestMapping("doUpdateObject")
    public JsonResult doUpdateObject(SysUser entity,Integer[] roleIds){
        sysUserService.updateObject(entity,roleIds);
        return new JsonResult("update ok");
    }

    //登录操作
    @RequestMapping("doLogin")
    public JsonResult doLogin(String username,String password){
        //1.获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.基于subject对象提交token到SecurityManager
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        subject.login(token);
        return new JsonResult("login ok");
    }
}
